﻿using System.IO;
using System.Text;
using UnityEngine;
using XLua;

public class LuaManager
{
    private static LuaManager _instance;
    public static LuaManager instance
    {
        get 
        {
            if (_instance == null)
                _instance = new LuaManager();
            return _instance; 
        }
    }

    public LuaEnv globalLuaEnv;

    public void InitGlobalLuaEnv()
    {
        globalLuaEnv = new LuaEnv();
        // require时调用
        globalLuaEnv.AddLoader((ref string filePath) =>
        {
            // Lua脚本读取位置
            string absPath = $"{Application.streamingAssetsPath}/LuaScript/{filePath.Replace('.', '/')}.lua";
            if (!File.Exists(absPath))
            {
                return Encoding.UTF8.GetBytes($"error('file path[{filePath}] not found!')\n");
            }
            string luaStr = File.ReadAllText(absPath);
            // 返回对应的lua文本字节
            return Encoding.UTF8.GetBytes(luaStr);
        });
        // 释放对应内存空间
        // GameLauncher.onDispose += () => { globalLuaEnv.Dispose(); };
    }
}